package com.zc.serveudpdemo.ui;

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.ActivityCompat;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import com.zc.serveudpdemo.R;
import com.zc.serveudpdemo.base.BaseActivity;
import com.zc.serveudpdemo.h264.RtpPacketEncode;
import com.zc.serveudpdemo.tcp.TcpHelper;
import com.zc.serveudpdemo.udp.ServeUdp;
import com.zc.serveudpdemo.utils.FiFoUsbStream;
import com.zc.serveudpdemo.utils.FileUtil;

import java.io.IOException;


public class MainActivity extends BaseActivity implements /*RtpPacketEncode.H264ToRtpLinsener,/*H264ReadListener */
        View.OnClickListener, TextWatcher {

    private final String TAG = MainActivity.class.getSimpleName();
    private Button btn;
    private EditText ed;
    private Button btnSaveH264;
    //    private ServeUdp serveUdp;
    private RtpPacketEncode mRtpPacketEncode;
    private String edStrIp = null;
    private TcpHelper mTcpHelper = null;

//    private ClientLastly client;
//    private StringBuffer receiveData = new StringBuffer();

//    private Handler handler = new Handler(new Handler.Callback() {
//        @Override
//        public boolean handleMessage(Message msg) {
//            if (msg.arg1 == 0x12) {
//                receiveData.append((String) msg.obj);
//                tv_showReceiveDataClient.setText(receiveData);
//                receiveData.append("\r\n");
//            }
//
//            return false;
//        }
//    });


    @Override
    protected void init(Bundle savedInstanceState) {
        setContentView(R.layout.activity_main);
        btn = findViewById(R.id.btn);
        btn.setOnClickListener(this);
        ed = findViewById(R.id.ed);
        ed.addTextChangedListener(this);
        btnSaveH264 = findViewById(R.id.btn_save);
        btnSaveH264.setOnClickListener(this);
        checkPermission();
    }

    /**
     * android6.0之后要动态获取权限
     */
    private void checkPermission() {
        // Storage Permissions
        final int REQUEST_EXTERNAL_STORAGE = 1;
        String[] PERMISSIONS_STORAGE = {Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE};
        try { //检测是否有写的权限
            int permission = ActivityCompat.checkSelfPermission(this, "android.permission.WRITE_EXTERNAL_STORAGE");
            if (permission != PackageManager.PERMISSION_GRANTED) {
                // 没有写的权限，去申请写的权限，会弹出对话框
                ActivityCompat.requestPermissions(this, PERMISSIONS_STORAGE, REQUEST_EXTERNAL_STORAGE);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {
        String edStr = ed.getText().toString();
        edStrIp = edStr;
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
//        client.close();
//        if (serveUdp != null) {
//            serveUdp.stop();
//            serveUdp = null;
//        }
        if (mTcpHelper != null) {
            mTcpHelper.stop();
            mTcpHelper = null;
        }
    }

//    @Override
//    public void h264ToRtpResponse(byte[] out, int len) {
//        if (serveUdp != null && out != null) {
//            serveUdp.send(out, len);
//        }
//    }

    @Override
    protected void revUsbStreamData(FiFoUsbStream fiFoUsbStream) {
        super.revUsbStreamData(fiFoUsbStream);
        searchFrame(fiFoUsbStream);
    }


    private void searchFrame(FiFoUsbStream fiFoUsbStream) {
        int len = fiFoUsbStream.getActualSize();
        byte[] data = new byte[len];
        fiFoUsbStream.FiFoRead(data, len);
        if (mTcpHelper != null && mTcpHelper.isConnected()) {
            mTcpHelper.sendBytes(data);
        }
//        for (int i = 0; i < len; i++) {
//            dataParse(data[i]);
//        }
//        if (client != null) {
//            client.send(data);
//        }
    }

    private int btnFlag = 0;
    private int btnSaveH264Flag = 0;

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn:
                if (btnFlag == 0) {
//                    serveUdp = new ServeUdp(edStrIp);
//                    mRtpPacketEncode = new RtpPacketEncode(this);
//                    mTcpHelper = TcpHelper.getInstance();
                    mTcpHelper=new TcpHelper(edStrIp);
//                    client = new ClientLastly();
//                    new Thread(client).start();
                    btn.setBackgroundColor(getResources().getColor(R.color.colorAccent));
                    btn.setText("停止视频流");
                    btnFlag = 1;
                } else {
//                    client.close();
//                    serveUdp.stop();
//                    serveUdp = null;
                    mTcpHelper.stop();
                    mTcpHelper = null;
                    btn.setText("发送视频流");
                    btn.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
                    btnFlag = 0;
                }
                break;
            case R.id.btn_save:
                if (btnSaveH264Flag == 0) {
                    btnSaveH264.setBackgroundColor(getResources().getColor(R.color.colorAccent));
                    btnSaveH264.setText("Stop");
                    startSaveH264();
                    btnSaveH264Flag = 1;
                } else {
                    btnSaveH264.setText("Save");
                    btnSaveH264.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
                    stopSaveH264();
                    btnSaveH264Flag = 0;
                }
                break;
            default:
                break;
        }
    }

//    private byte[] naluBuffer = new byte[5 * 1024 * 1024];
//    private byte[] tempBuffer = new byte[4];
//    private int naluLen = 0;
//    private int state = 0;
//
//    private int dataParse(byte c) {
//        switch (state) {
//            case 0:
//                if (c != 0) {
//                    naluBuffer[naluLen] = c;
//                    naluLen++;
//                } else {
//                    state = 1;
//                    tempBuffer[0] = c;
//                }
//                break;
//            case 1:
//                if (c == 0) {
//                    state = 2;
//                    tempBuffer[1] = c;
//                } else {
//                    state = 0;
//                    naluBuffer[naluLen++] = tempBuffer[0];
//                    naluBuffer[naluLen++] = c;
//                }
//                break;
//            case 2:
//                if (c == 0) {
//                    state = 3;
//                    tempBuffer[2] = c;
//                } else if (c == 0x01) {
//                    state = 0;
//                    if (naluLen > 0) {
//                        readFrameData(naluBuffer, naluLen);
//                        naluLen = 0;
//                        return 1;
//                    }
//                } else {
//                    state = 0;
//                    naluBuffer[naluLen++] = tempBuffer[0];
//                    naluBuffer[naluLen++] = tempBuffer[1];
//                    naluBuffer[naluLen++] = c;
//                }
//                break;
//            case 3:
//                if (c == 0x01) {
//                    state = 0;
//                    if (naluLen > 0) {
//                        readFrameData(naluBuffer, naluLen);
//                        naluLen = 0;
//                        return 1;
//                    }
//                } else {
//                    state = 0;
//                    naluLen = 0;
//                }
//                break;
//            default:
//                break;
//        }
//        return 0;
//    }
//
//    private void readFrameData(byte[] bytes, int len) {
//        if (mRtpPacketEncode != null) {
//            mRtpPacketEncode.h264ToRtp(bytes, len);
//        }
//    }


}
